namespace Umbraco.Ecommerce.WebShop.UserControls.QuickPay
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Security.Cryptography;
    using System.Globalization;
    using System.Text;
    using System.Net;
    using System.IO;
    using Umbraco.Ecommerce.BusinessLogic;

    /// <summary>
    ///	Handles online payments, integrates with QuickPay paymentgateway.
    /// </summary>
    public class PaymentForm : System.Web.UI.UserControl
    {
        protected System.Web.UI.WebControls.Literal lttprice;
        protected System.Web.UI.WebControls.Literal lttOrderID;
        protected System.Web.UI.WebControls.Literal lttPaymentCardIcons;
        protected System.Web.UI.WebControls.Literal lttFields;

        private Order getOrder()
        {
            try
            {
                System.Collections.ArrayList al = Order.GetSessionOrders(Request.QueryString["session"]);
                al.Reverse();
                return (Order)al[0];
            }
            catch { }
            return null;
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            Order o = getOrder();
            if (Store.QuerySettingsFileOutput("/settings/quickpay/test").Trim() != "")
            {
                Response.Write("TESTMODE");
            }
            if (Request.Form.Get("cardnum") != null)
            {
                if (Store.QuerySettingsFileOutput("/settings/quickpay/test").Trim() != "")
                {
                    // If the store is in test mode just simulate that everything went ok


                    //Umbraco.Ecommerce.WebShop.UserControls.Checkout.DoOrderFinalisation(o);
                    Response.Redirect(Store.QuerySettingsFileOutput("/settings/quickpay/accepturl"));
                }
                else
                {
                    HandlePaymentRequest();
                }
            }
            else
                if (Request.QueryString["session"] != null)
                {
                    if (o != null)
                    {
                        string msgtype = Store.QuerySettingsFileOutput("/settings/quickpay/msgtype");
                        string currency = Store.QuerySettingsFileOutput("/settings/quickpay/currency");
                        string accepturl = Store.QuerySettingsFileOutput("/settings/quickpay/accepturl");
                        string declineurl = Store.QuerySettingsFileOutput("/settings/quickpay/declineurl");
                        string posc = Store.QuerySettingsFileOutput("/settings/quickpay/posc");
                        string merchant = Store.QuerySettingsFileOutput("/settings/quickpay/merchant");
                        string md5checkword = Store.QuerySettingsFileOutput("/settings/quickpay/md5checkword");
                        string proxypath = Store.QuerySettingsFileOutput("/settings/quickpay/proxypath");

                        lttOrderID.Text = o.OrderId.ToString();
                        lttprice.Text = o.TotalIncVAT.ToString("c", Store.NumberFormatInfo).ToLower().Replace("kr", "DKK");
                        lttFields.Text += "<input type='hidden' value='00" + o.OrderId + "' name='ordernum' id='ordernum'>";
                        lttFields.Text += "<input type='hidden' value='" + decimal.Floor(o.TotalIncVAT * 100) + "' name='amount'>";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + msgtype + "\" name=\"msgtype\" />";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + currency + "\" name=\"currency\" />";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + accepturl + "\" name=\"accepturl\">";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + declineurl + "\" name=\"declineurl\">";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + posc + "\" name=\"posc\">";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + merchant + "\" name=\"merchant\">";
                        lttFields.Text += "<input type=\"hidden\" value=\"" + md5checkword + "\" name=\"md5checkword\">";

                        lttPaymentCardIcons.Text += "<img src=\"" + proxypath + "/images/1.gif\">";
                        lttPaymentCardIcons.Text += "<img src=\"" + proxypath + "/images/2.gif\">";
                        lttPaymentCardIcons.Text += "<img src=\"" + proxypath + "/images/3.gif\">";
                        lttPaymentCardIcons.Text += "<img src=\"" + proxypath + "/images/4.gif\">";
                        lttPaymentCardIcons.Text += "<img src=\"" + proxypath + "/images/5.gif\">";
                    }
                    else
                    {
                        Response.Write("ERROR READING ORDER!!");
                    }

                }
                else
                {
                    Response.Write("ERROR READING SESSIONID!!");
                }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void HandlePaymentRequest()
        {
            // Read data from form.
            string cardnumber = Request.Form.Get("cardnum");
            string amount = Request.Form.Get("amount");
            string expirationdate = Request.Form.Get("eyear") + Request.Form.Get("emonth");
            string ordernum = Request.Form.Get("ordernum");
            string mycurrency = Request.Form.Get("currency");
            string cvd = Request.Form.Get("cvc");
            string msgtype = Request.Form.Get("msgtype");
            string posc = Request.Form.Get("posc");
            string merchant = Request.Form.Get("merchant");
            string md5checkword = Request.Form.Get("md5checkword");
            string accepturl = Request.Form.Get("accepturl");
            string declineurl = Request.Form.Get("declineurl");

            // Calculate md5 checkvalue
            string checkValue = msgtype + cardnumber + amount + expirationdate +
                posc + ordernum + mycurrency + cvd +
                merchant + md5checkword;
            string md5Check = QuickPayUtil.md5(checkValue);

            // Construct POST string
            string strBody = "msgtype=" + msgtype;
            strBody += "&cardnumber=" + cardnumber;
            strBody += "&amount=" + amount;
            strBody += "&expirationdate=" + expirationdate;
            strBody += "&posc=" + posc;
            strBody += "&ordernum=" + ordernum;
            strBody += "&currency=" + mycurrency;
            strBody += "&cvd=" + cvd;
            strBody += "&merchant=" + merchant;
            strBody += "&md5check=" + md5Check;

            umbraco.presentation.nodeFactory.Node n = umbraco.presentation.nodeFactory.Node.GetCurrent();
            string myval = n.Name;

            // Convert the POST string to bytearray
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(strBody);

            // The URI to call
            String quickpayurl = "https://secure.quickpay.dk/transaction.php";

            // Call QuickPay URI
            WebRequest wreq;
            WebResponse wres;
            StreamReader sr;
            string content;
            wreq = HttpWebRequest.Create(quickpayurl);
            wreq.Method = "POST";
            wreq.ContentType = "application/x-www-form-urlencoded";
            wreq.ContentLength = data.Length;
            Stream newStream = wreq.GetRequestStream();
            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response from QuickPay
            wres = wreq.GetResponse();
            sr = new StreamReader(wres.GetResponseStream());
            content = sr.ReadToEnd();
            sr.Close();

            // Make response helper object
            QuickPayResponseContent quickPayResponseContent = new QuickPayResponseContent(content);

            // Remove the newline character for the response, so the response is visble in the redirect URL. Newline is not allowed in URLs
            string contentWithoutNewline = content.Replace("\n", "");
            if (quickPayResponseContent.Qpstat.Equals("000")) // The Authorisation was succesful
            {
                // Confirm the order and send emails to the customer and shopowner!
                int orderid = int.Parse(ordernum);
                Order o = new Order(orderid);
                //Umbraco.Ecommerce.WebShop.UserControls.Checkout.DoOrderFinalisation(o);

                Response.Redirect(accepturl);
            }
            else // Something went wrong. The reason can be found in qpstatmsg
            {
                Response.Redirect(declineurl + "?message=" + contentWithoutNewline);
            }
        }
    }
}
